<template>
  <PageWrapper title="技术视野">
    <div style="display: flex; justify-content: center">
      <a-input-search
        v-model:value="searchText"
        placeholder="请输入文章名称"
        style="width: 600px; margin-bottom: 16px"
        enter-button
        @search="onSearch"
        @change="onSearch"
      />
      <a-button type="primary" style="margin-left: 5px" @click="showDrawer">新增</a-button>
    </div>
    <div>
      <a-card :bodyStyle="{ padding: '24px' }">
        <div v-for="(i, idx) in dataResults" :key="idx" :style="{ padding: '5px' }">
          <a :href="i.url" @click="(e) => jump(e, i.url)">
            {{ i.title }}
          </a>
          <div style="float: right">
            <a style="padding: 0 5px" @click="(e) => editUrl(e, i)">编辑</a>
            <a style="padding: 0 5px" @click="(e) => deleteUrl(e, i)">删除</a>
          </div>
          <span :style="{ float: 'right' }">{{ dayjs(i.publish_date).format('YYYY-MM-DD') }}</span>
        </div>
        <a-pagination
          v-model:current="current"
          v-if="!searchText"
          show-quick-jumper
          :total="totalResults"
          v-model:page-size="pageSize"
          @change="onChange"
          :style="{ float: 'right', marginTop: '10px' }"
        />
      </a-card>
    </div>
    <a-drawer
      title="新增文章"
      :width="720"
      :open="open"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose"
    >
      <a-form :model="form" :rules="rules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="链接名称" name="urlName">
              <a-input
                v-model:value="form.title"
                style="width: 100%"
                placeholder="请输入链接名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="链接" name="url">
              <a-input v-model:value="form.url" style="width: 100%" placeholder="请输入链接地址" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="发布日期" name="publish_date">
              <a-date-picker v-model:value="form.publish_date" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <template #extra>
        <a-space>
          <a-button @click="onClose">取消</a-button>
          <a-button type="primary" @click="onSave">保存</a-button>
        </a-space>
      </template>
    </a-drawer>
    <contextHolder />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { PageWrapper } from '@/components/Page';
  import axios from '@/utils/myHttp';
  import { Api } from '@/api/technicalVision';
  import { debounce, get } from 'lodash-es';
  import type { Rule } from 'ant-design-vue/es/form';
  import { notification } from 'ant-design-vue';
  import dayjs from 'dayjs';

  const [api, contextHolder] = notification.useNotification();

  const current = ref<number>(1);
  const pageSize = ref<number>(10);
  const dataResults = ref<Website[]>([]);
  const totalResults = ref<number>(0);
  const originData = ref<Website[]>([]);
  const searchText = ref<string>('');
  const open = ref<boolean>(false);

  const form = reactive({
    id: '',
    url: '',
    title: '',
    publish_date: '',
  });

  const rules: Record<string, Rule[]> = {
    url: [{ required: true, message: '请输入链接' }],
    title: [{ required: true, message: '请输入链接名称' }],
    publish_date: [{ required: false, message: '请选择日期' }],
  };

  const onChange = (pageNumber: number) => {
    console.log('Page: ', pageNumber);
    getData();
  };

  interface Website {
    url: string;
    title: string;
    publish_date: Date;
  }

  const getData = () => {
    axios
      .get(`${Api.TECHNICALVISION}?page=${current.value}&pageSize=${pageSize.value}`)
      .then((response) => {
        console.log('🚀 ~ results ~ response:', response.data);
        const _response = get(response, 'data');
        dataResults.value = _response.data;
        originData.value = JSON.parse(JSON.stringify(_response.data));
        totalResults.value = _response.total;
      });
  };

  getData();

  const jump = (e, url) => {
    e.preventDefault();
    window.open(url, '_blank');
  };

  const showDrawer = (obj) => {
    form.id = obj?.id;
    form.title = obj?.title;
    form.url = obj?.url;
    form.publish_date = obj?.publish_date;
    open.value = true;
  };

  // 前端搜索功能
  const onSearch = () => {
    const fn = () => {
      console.log('🚀 ~ fn ~ searchText.value:', searchText.value);
      if (searchText.value) {
        dataResults.value = dataResults.value.filter((item) => {
          // 转小写，再判断
          const lowerStr = item.title.toLowerCase();
          const lowerSearchStr = searchText.value.toLowerCase();
          return lowerStr.includes(lowerSearchStr);
        });
      } else {
        console.log('无值', originData.value);
        dataResults.value = JSON.parse(JSON.stringify(originData.value));
      }
    };
    debounce(fn, 500)();
  };
  const editUrl = (e, i) => {
    e.preventDefault();
    showDrawer({
      id: i.id,
      title: i.title,
      url: i.url,
      publish_date: dayjs(i.publish_date),
    });
  };

  // 删除链接
  const deleteUrl = (e, item) => {
    console.log('🚀 ~ deleteUrl ~ item:', item);
    e.preventDefault();
    axios.delete(`${Api.TECHNICALVISION}/${item.id}`).then(
      (response) => {
        console.log('🚀 ~ results ~ response:', response.data);
        // 原结构,response.data.data，这里去掉第一层的data
        const _response = get(response, 'data');
        if (_response.success) {
          getData();
        } else {
          api.info({
            message: _response.code,
            description: _response.message,
            placement: 'topRight',
          });
        }
      },
      (error) => {
        api.info({
          message: error.code,
          description: error.message,
          placement: 'topRight',
        });
      },
    );
  };

  const onClose = () => {
    open.value = false;
  };
  const onSave = () => {
    open.value = false;
    const _form = JSON.parse(JSON.stringify(form));
    _form.publish_date = dayjs(_form.publish_date).format('YYYY-MM-DD');
    axios[form.id ? 'put' : 'post'](
      `${Api.TECHNICALVISION}/${_form.id ? _form.id : ''}`,
      _form,
    ).then(
      (response) => {
        console.log('🚀 ~ results ~ response:', response.data);
        // 原结构,response.data.data，这里去掉第一层的data
        const _response = get(response, 'data');
        if (_response.success) {
          getData();
        } else {
          api.info({
            message: _response.code,
            description: _response.message,
            placement: 'topRight',
          });
        }
      },
      (error) => {
        api.info({
          message: error.code,
          description: error.message,
          placement: 'topRight',
        });
      },
    );
  };
</script>
<style scoped>
  .favicon {
    width: 16px;
    margin-top: -4px;
    margin-right: 5px;
  }
</style>
